package com.example.demo.Shiro;

import com.example.demo.Entity.SysPermission;
import com.example.demo.Entity.SysRole;
import com.example.demo.Entity.UserInfo;
import com.example.demo.Service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import javax.annotation.Resource;

public class MyShiroRealm extends AuthorizingRealm {
    @Resource
    private UserService userService;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo simpleAuthorizationInfo=new SimpleAuthorizationInfo();
        UserInfo userInfo=(UserInfo)principalCollection.getPrimaryPrincipal();
        for(SysRole role: userInfo.getRoles()){
            simpleAuthorizationInfo.addRole(role.getRole());
            for(SysPermission permission : role.getPermissions())
                simpleAuthorizationInfo.addStringPermission(permission.getPermission());
        }
        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String username=(String)authenticationToken.getPrincipal();
        UserInfo userInfo=userService.findByUserName(username);
        if(userInfo==null){
            return null;
        }
        SimpleAuthenticationInfo simpleAuthenticationInfo=new SimpleAuthenticationInfo(
                userInfo.getUserName(),
                userInfo.getPassword(),
                ByteSource.Util.bytes(userInfo.getSalt()),
                userInfo.getName()
        );
        return simpleAuthenticationInfo;
    }
}
